package com.xiebishe.mylibrary.common.pageStatus.centerHandler;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;


import com.xiebishe.mylibrary.common.pageStatus.AbstractStatusHandler;

import java.util.WeakHashMap;

public abstract class NormalStatusHandler<VIEW extends ViewGroup> extends AbstractStatusHandler<VIEW> {
    private WeakHashMap<View, Integer> storeVisibility = new WeakHashMap<>();

    public NormalStatusHandler(@NonNull VIEW layout) {
        super(layout);
    }

    @Override
    protected final boolean onAddLoadingView(@NonNull View loadingView, @NonNull VIEW layout) {
        addToLayout(loadingView, layout);
        return true;
    }

    @Override
    protected final boolean onRemoveLoadingView(@NonNull View loadingView, @NonNull VIEW layout) {
        removeView(loadingView, layout);
        return true;
    }

    @Override
    protected final boolean onAddEmptyView(@NonNull View loadingView, @NonNull VIEW layout) {
        addToLayout(loadingView, layout);
        return true;
    }

    @Override
    protected final boolean onRemoveEmptyView(@NonNull View loadingView, @NonNull VIEW layout) {
        removeView(loadingView, layout);
        return true;
    }

    @Override
    protected final boolean onAddErrorView(@NonNull View loadingView, @NonNull VIEW layout) {
        addToLayout(loadingView, layout);
        return true;
    }

    @Override
    protected final boolean onRemoveErrorView(@NonNull View loadingView, @NonNull VIEW layout) {
        removeView(loadingView, layout);
        return true;
    }


    abstract protected void addToLayout(@NonNull View view, @NonNull VIEW layout);

    abstract protected void removeView(@NonNull View view, @NonNull VIEW layout);

    protected void setAllGone(@NonNull VIEW layout) {
        setAllVisibility(layout, View.GONE);
    }

    protected void setAllInvisible(@NonNull VIEW layout) {
        setAllVisibility(layout, View.INVISIBLE);
    }

    protected void setAllVisible(@NonNull VIEW layout) {
        setAllVisibility(layout, View.VISIBLE);
    }

    protected void restoreLastVisibility(@NonNull VIEW layout) {
        int childCount = layout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = layout.getChildAt(i);
            Integer integer = storeVisibility.get(childAt);
            int visibility;
            if(integer==null) visibility = View.VISIBLE; else visibility = integer;
            childAt.setVisibility(visibility);
        }
    }

    private void setAllVisibility(@NonNull VIEW layout, int visibility) {
        int childCount = layout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = layout.getChildAt(i);
            storeVisibility.put(childAt, childAt.getVisibility());
            childAt.setVisibility(visibility);
        }
    }
}
